from flask import request, g, current_app, jsonify
from . import api
from ihome.utils.common import get_user_info
from ihome.models import Order, House
from ihome.utils.response_code import RET
import datetime
from ihome import db


@api.route("/orders/cancel", methods=["PUT"])
@get_user_info
def cancel_order_status():
    """取消订单 后端接口   orders.js // lorders.js  """
    login_user = g.user
    order_id = request.json.get("order_id")
    if not order_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not login_user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 查询 当前待接单状态的订单 是否存在
    try:
        order_obj = Order.query.filter(Order.id == order_id,  Order.status == "WAIT_ACCEPT").first()
    except Exception as err:
        current_app.logger.error(err)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询订单对象异常")
    if not order_obj:
        return jsonify(errno=RET.NODATA, errmsg="订单不存在")

    order_obj.status = "CANCELED"
    try:
        db.session.commit()
    except Exception as err:
        db.session.rollback()
        current_app.logger.error(err)
        return jsonify(errno=RET.DBERR, errmsg="数据库修改订单状态异常")

    return jsonify(errno=RET.OK, errmsg="OK")


@api.route("/orders", methods=["POST"])
@get_user_info
def orders():
    """添加订单后端接口"""

    # 获取参数
    user = g.user
    house_id = request.json.get("house_id")      # 房屋id
    start_data = request.json.get("start_date")  # 开始日期
    end_data = request.json.get("end_date")      # 结束时间

    # 非空判断
    if not all([house_id, start_data, end_data]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        start_data = datetime.datetime.strptime(start_data, "%Y-%m-%d")
        end_data = datetime.datetime.strptime(end_data, "%Y-%m-%d")
        assert start_data < end_data, Exception("结束时间必须大于开始时间")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登陆")

    # 逻辑处理
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询房屋对象异常")

    if not house:
        return jsonify(errno=RET.NODATA, errmsg="房屋不存在")

    if user.id == house.user_id:
        return jsonify(errno=RET.ROLEERR, errmsg="房东不能预定")

    # 判断该房屋指定时间内是否有冲突订单
    try:                                             # 预定结束时间>开始时间       预定起始时间<结束时间
        filters = [Order.house_id == house_id, Order.end_date > start_data, Order.begin_date < end_data]
        order_count = Order.query.filter(*filters).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询冲突订单异常")
    if order_count > 0:
        return jsonify(errno=RET.DATAERR, errmsg="订单冲突")

    # 创建订单对象
    order = Order()
    order.user_id = user.id
    order.house_id = house_id
    order.begin_date = start_data
    order.end_date = end_data
    order.days = (start_data - end_data).days
    order.house_price = house.price
    order.amount = (start_data - end_data).days * house.price

    house.order_count += 1

    # 数据提交到数据库
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="OK", data={"order_id": order.id})


@api.route("/orders/comment", methods=["PUT"])
@get_user_info
def order_comment():
    """评论"""
    data_json = request.json
    order_id = data_json.get("order_id")
    comments = data_json.get("comment")

    if not all([order_id,comments]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_COMMENT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据出错")

    if not order:
        return jsonify(errno=RET.NODATA, errmsg = "订单不存在")

    order.comment = comments
    order.status = "COMPLETE"

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg= "保存数据失败")

    return jsonify(errno=RET.OK, errmsg= "OK")


@api.route("/orders", methods=["PUT"])
@get_user_info
def change_order_status():
    """接收或拒绝"""
    user_id = g.user.id
    data_json = request.json
    order_id = data_json.get("order_id")
    action = data_json.get("action")

    if not all([order_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        order = Order.query.filter(Order.id==order_id,Order.status == "WAIT_ACCEPT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="参数查询错误")

    if not order:
        return jsonify(errno=RET.NODATA, errmsg="未查询到订单")

    if user_id != order.house.user_id:
        return jsonify(errno=RET.ROLEERR, errmsg="用户身份错误")

    if "accept" == action:
        order.status = "WAIT_COMMENT"
    elif "reject" == action:
        order.status = "REJECTED"
        reason = data_json.get("reason")
        if not reason:
            return jsonify(errno= RET.PARAMERR, errmsg= "填写拒单原因")
        order.comment = reason

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存数据异常")
    return jsonify(errno=RET.OK, errmsg="OK")


@api.route("/orders")
@get_user_info
def get_orders():
    """获取订单"""
    user_id = g.user.id
    role = request.args.get("role")
    if not role:
        return jsonify(errno=RET.PARAMERR, errmag="参数错误")
    if role not in("custom", "landlord"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        if "custom" == role:
            orders = Order.query.filter(Order.user_id == user_id).order_by(Order.create_time.desc()).all()
        elif "landlord" == role:
            houses = House.query.filter(House.user_id == user_id).all()
            houses_ids = [house.id for house in houses]
            orders = Order.query.filter(Order.house_id.in_(houses_ids)).order_by(Order.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg="数据查询错误")
    orders_dict_li = []
    for order in orders:
        orders_dict_li.append(order.to_dict())
    return jsonify(errno=RET.OK, errmsg="OK", data={"orders":orders_dict_li})
